﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommunityToolkitMvvmDemo.ViewModels
{
    /// <summary>
    ///  自定义消息类型 
    /// </summary>
    record StringMessage(string Message);


    /// <summary>
    /// IRecipient 可以让类来接收消息，RequestMessage 可以让send 时，有返回值
    /// </summary>
    public class Receiver1ViewModel: ObservableObject , IRecipient<RequestMessage<string>>  
    {
        private int number =5;
        public int Number
        {
            get { return number; }
            set {
                //if (SetProperty(ref number, value)) // true 表示属性已经发生改变，false 表示值未改变
                //{
                //    WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<int>(this, nameof(Number),default,value));
                //}
                if (value != number)
                {
                    WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<int>(this, nameof(Number), number, value));
                    number = value;
                    OnPropertyChanged();
                }
            }
        }

        public Receiver1ViewModel()
        {
            WeakReferenceMessenger.Default.Register(this);
            WeakReferenceMessenger.Default.Register<StringMessage>(this, Receive1); // 接收者(消息订阅者)以及接收后的回调，注册的消息类型是 StringMessage              
            WeakReferenceMessenger.Default.Register<ValueChangedMessage<string>>(this, Receive2);
            WeakReferenceMessenger.Default.Register<PropertyChangedMessage<int>>(this, Receive3);
        }

        /// <summary>
        ///  IRecipient 接口中的方法   
        /// </summary>
        public void Receive(RequestMessage<string> message) 
        {
            Debug.WriteLine(" request message reveived ~~~");    
            message.Reply("hello ~~~~");
        }

        /// <summary>
        /// 接收后的回调
        /// </summary>
        private void Receive1(object recipient, StringMessage message)
        {
           Debug.WriteLine(message.Message);
        }

        /// <summary>
        /// 接收后的回调
        /// </summary>
        private void Receive2(object recipient, ValueChangedMessage<string> message)
        {
            Debug.WriteLine(message.Value);
        }

        /// <summary>
        /// 接收后的回调
        /// </summary>
        private void Receive3(object recipient, PropertyChangedMessage<int> message)
        {
            Debug.WriteLine( $"Property {message.PropertyName}  from { message.Sender.GetType().Name } received , old value is { message.OldValue } , new value is { message.NewValue}"   );
        }


    }
}
